package cn.tedu.vrd08.controller;

import cn.tedu.vrd08.entity.User;
import cn.tedu.vrd08.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session) {
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                if (rem != null) {//代表记住用户名和密码
                    //通过Cookie保存用户名和密码
                    Cookie c1 = new Cookie("username", user.getUsername());
                    Cookie c2 = new Cookie("password", user.getPassword());
                    //设置保存时间
                    c1.setMaxAge(60 * 60 * 24 * 30 * 828);
                    //把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);

                }
                session.setAttribute("user", u);
                return 1;
            } else {
                return 3;
            }
        }
        return 2;
    }

    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user");
    }


}
